package com.talent.basecontroller.advice;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.talent.basecontroller.message.ReturnMessageInfo;
import com.talent.basecontroller.message.ReturnStatusInfo;
import com.talent.basecontroller.exception.DuplicateSubmitException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhumenglong on 2017/5/16.
 */
@ControllerAdvice
public class BaseControllerAdvice {
    private static Logger log = LoggerFactory.getLogger(BaseControllerAdvice.class);
    /**
     * 处理自定义异常
     *
     * @param response
     *            http响应
     * @throws IOException
     */
    @ExceptionHandler({ DuplicateSubmitException.class })
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public void processBusinessException(Exception e, HttpServletResponse response) throws IOException {
        log.error(e.getMessage(), e);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        // 返回500错误
        resultMap.put(ReturnStatusInfo.getKey(ReturnStatusInfo.MessageStatus.KEY500), ReturnStatusInfo.getValue(ReturnStatusInfo.MessageStatus.KEY500));
        // 返回500描述信息
        resultMap.put(ReturnMessageInfo.getKey(ReturnMessageInfo.Message.KEY500), e.getMessage());
        writeValue(response, resultMap);
    }

    /**
     * 返回信息
     *
     * @param response
     *            http响应
     * @param value
     *            待转换JSON数据
     * @throws IOException
     */
    private void writeValue(HttpServletResponse response, Object value) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        mapper.writeValue(response.getWriter(), value);
    }
}
